<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form divClass" v-if="headerShow">
                <div>
                    <a-form :model="queryData" size="small" layout="inline">
                        <a-form-item label="织布单号" label-col-flex="80px">
                            <a-input allow-clear :style="{ width: '213px' }" class="bacClass" placeholder=""
                                v-model="queryData.jiludanhao" @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="客户订单号" label-col-flex="80px">
                            <a-input allow-clear :style="{ width: '213px' }" class="bacClass" placeholder=""
                                v-model="queryData.kehudingdanhao" @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="客户名称" label-col-flex="80px">
                            <a-input allow-clear :style="{ width: '213px' }" class="bacClass" placeholder=""
                                v-model="queryData.kehuName" @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="机台号" label-col-flex="80px">
                            <a-input allow-clear :style="{ width: '213px' }" class="bacClass" placeholder=""
                                v-model="queryData.machineCode" @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item label="打印时间" label-col-flex="80px">
                            <a-range-picker  popup-container="html"  v-model="queryData.tiemsData"
                                style="width: 275px;" class="bacClass" @clear="timeClears"/>
                        </a-form-item>
                    </a-form>
                </div>
                <div class="my-tool-bar">
                    <Toolbar :items="[
                        '补打',
                        `${permissionStore.hasPermisson('bfdylb.cx') ? '查询' : ''}`,
                        `${permissionStore.hasPermisson('bfdylb.zf') ? '作废' : ''}`]" @select="cx" @dyBoufei="dyBf"
                        @cel="fexDels" @buDa="buDas">
                    </Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <template #pageTabel>
            <a-spin :loading="queryData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                    :suppressDragLeaveHidesColumns="true" class='ag-theme-alpine' :localeText="localeText1"
                    rowSelection="multiple" @grid-ready="gridReady" @columnVisible="onColumnVisible"
                    @SelectionChanged="aggridFs.clickAllSelectors" @FilterChanged="aggridFs.onFilterChanged"
                    @columnResized="onColumnResized" @columnMoved="onColumnMoved" style="height:100%"
                    :defaultColDef="defaultColDef" :rowData="table.dataList" :columnDefs="tc">
                </AgGridVuesCopys>
            </a-spin>
        </template>
        <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" style="justify-content: center" :page-size="pagination.pageSize"
            :current="pagination.page" />
    </pageTabelLayout>

    <a-drawer ok-text='关闭' :drawer-style="{ 'zIndex': 9999 }" @ok="bc" :width="'100%'" :height="'100%'" :visible="bfShowAdd"
        placement="bottom" :hide-cancel="true">
        <template #title>
            模版
        </template>
        <iframe v-if="bfShowAdd" style="width: 100%;height: 100%;" :src="srcUrl"></iframe>
    </a-drawer>
</template>
<script lang='ts' setup>
import { number } from 'echarts/core';
import { reactive, toRefs, ref, onMounted } from 'vue'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import { post } from '@/api/http'
import { url } from 'inspector';

import { Message, Modal } from '@arco-design/web-vue';
import { IconDoubleUp, IconDoubleDown } from '@arco-design/web-vue/es/icon';
import { localeText } from '@/api/aggridZw'
import usePermission from '@/store/modules/permission'
import { pagingList } from '@/api/paging'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import useAgGridFilterSelector from '@/utils/aggridFilterAllSelect'
const aggridFs = useAgGridFilterSelector()
const pagingList1: any = ref(pagingList)
const permissionStore = usePermission()
const localeText1: any = ref(localeText)


const queryData: any = reactive({
    firm: "",
    clothType: "",
    tiemsData:['','']
});
const headerShow = ref<boolean>(true)
function doRefresh() {
    queryData.pageLoading = true
    updateGridState01()
    post({
        url: 'planSingle/clothfiy/getPageInfo',
        data: {
            page: pagination.page,
            size: pagination.pageSize,
            planOrderCode: queryData.jiludanhao,
            customOrderNo: queryData.kehudingdanhao,
            customName: queryData.kehuName,
            machineCode: queryData.machineCode,
            startTime: queryData.tiemsData[0],
            endTime: queryData.tiemsData[1],
        }
    }).then(({ data, code }: any) => {
        if (code === 200) {
            table.handleSuccess(data.list);
            aggridFs.resetAgFs()
            // pagination.setTotalSize(data.total);
            gridOption.value.setRowData(data.list);
            total.value = data.total;
        }
    })
        .catch(console.log).finally(() => {
            queryData.pageLoading = false
        })
}
const total = ref(10);
const page = ref(1);
const size = ref(10);
function PageSize(val: any) {
    pagination.page = val
    doRefresh();
}
function change1(val: any) {
    pagination.pageSize = val
    doRefresh();
}
const cx = () => {
    pagination.page = 1
    doRefresh()
}

const dyBf = () => {

}
onMounted(() => {
    doRefresh()
})
const { selectedRowKeys } = useRowSelection()

const table = useTable()

const pagination = usePagination(doRefresh)

const rowKey = useRowKey("id")

const tableColumns = useTableColumn([
    {
        title: "织布单号",
        key: "planOrderCode",
        dataIndex: "planOrderCode",
        width: 150,
    },
    {
        title: "生产单号",
        key: "produceCode",
        dataIndex: "produceCode",
        width: 150,
    },
    {
        title: "客户订单号",
        key: "customOrderNo",
        dataIndex: "customOrderNo",
        width: 120,
    },
    {
        title: "客户名称",
        key: "customName",
        dataIndex: "customName",
        width: 150,
    },
    {
        title: "机台号",
        key: "machineCode",
        dataIndex: "machineCode",
        width: 150,
    },
    {
        title: "机布号",
        key: "machineGreyCode",
        dataIndex: "machineGreyCode",
        width: 150,
    },
    {
        title: "匹号",
        key: "horseNo",
        dataIndex: "horseNo",
        width: 150,
    },
    {
        title: "针筒",
        key: "workDrum",
        dataIndex: "workDrum",
        width: 150,
    },
    {
        title: "坯布编号",
        key: "greyCode",
        dataIndex: "greyCode",
        width: 150,
    },
    {
        title: "坯布名称",
        key: "greyName",
        dataIndex: "greyName",
        width: 150,
    },
    {
        title: "颜色",
        key: "colorName",
        dataIndex: "colorName",
        width: 150,
    },
    {
        title: "门幅",
        key: "width",
        dataIndex: "width",
        width: 150,
    },
    {
        title: "抽针",
        key: "drawnNeedleState",
        dataIndex: "drawnNeedleState",
        slotName: 'drawnNeedleState',
        width: 150,
    },
    {
        title: "克重",
        key: "weight",
        dataIndex: "weight",
        width: 150,
    },
    {
        title: "开始匹号",
        key: "startHorseNo",
        dataIndex: "startHorseNo",
        width: 150,
    },
    {
        title: "纱批",
        key: "yarnBatch",
        dataIndex: "yarnBatch",
        width: 150,
    },
    {
        title: "加工单位",
        key: "outSouringCompany",
        dataIndex: "outSouringCompany",
        width: 150,
    },
    {
        title: "打印时间",
        key: "createTime",
        dataIndex: "createTime",
        width: 150,
    },
    {
        title: "作废状态",
        key: "obsoleteState",
        dataIndex: "obsoleteState",
        slotName: 'obsoleteState',
        width: 150,
        fixed: 'right'
    }
])

let tc: any = tableColumns.map((o) => {

    let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed']
    }
    if (o.slotName === 'drawnNeedleState') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj["width"] = 100
        obj['cellRenderer'] = {
            template: `<span>{{a==0?'圆筒':'抽针'}}</span>`,
            setup(props: any) {
                return {
                    a: props.params.data.drawnNeedleState
                }
            }

        }
    }
    if (o.slotName === 'obsoleteState') {
        obj['resizable'] = false
        obj['sortable'] = false
        obj["lockPosition"] = "right"
        obj["width"] = 100
        obj['cellRenderer'] = {
            template: `<el-tag v-if='a.obsoleteState == 0' type="success">正常</el-tag>
            <el-tag v-if='a.obsoleteState == 1' type="info">作废</el-tag>
            `,
            setup(props: any) {
                return {
                    a: props.params.data
                }
            }

        }
        obj['filterParams'] = {
      valueFormatter: function (params: any) {
        return params.value == '0'
          ? '正常'
          : params.value == '1'
          ? '作废'
          : ''
      },
    }
    }

    return obj
})

let a = [{
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    //lockPosition: "left",
}]
tc = a.concat(tc)

const dataList = ref('1')
// 表格准备事件
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    // flex: 1
}
const huiche = () => {
    doRefresh();
}
const handleSearch = (val: any) => {
    mohuchax({ recordCode: val }, 1)
}
const focusSel = () => {
    mohuchax({ recordCode: '' }, 1)
}
const handleSearch2 = (val: any) => {
    mohuchax({ customOrderNo: val }, 2)
}
const focusSel2 = () => {
    mohuchax({ customOrderNo: '' }, 2)
}
const handleSearch3 = (val: any) => {
    mohuchax({ customName: val }, 3)
}
const focusSel3 = () => {
    mohuchax({ customName: '' }, 3)
}
async function mohuchax(val: any, state: any) {
    const res = await post({
        url: 'planSingle/clothfiy/getDropValue',
        data: val
    })
    if (res.code == 200) {
        if (state == 1) {
            queryData.jiludanhaos = res.data
        }
        if (state == 2) {
            queryData.kehudingdanhaos = res.data
        }
        if (state == 3) {
            queryData.kehuNames = res.data
        }
    }
}

const fexDels = () => {
    if (gridOption.value.getSelectedRows().length == 0) {
        Message.error('请勾选数据')
        return false
    }
    Modal.confirm({
        title: '系统提示',
        content: '是否作废',
        onOk() {
            post({
                url: "planSingle/clothfiy/obsolete",
                data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
            }).then((res: any) => {
                if (res.code === 200) {
                    doRefresh()
                    Message.success(res.message)
                } else {
                    Message.error(res.message)
                }
            })
        }
    })
}

const srcUrl: any = ref()

const buDas = () => {
    if (gridOption.value.getSelectedRows().length == 0) {
        Message.error('请勾选数据')
        return
    }
    let DataListP = gridOption.value.getSelectedRows().map((res) => res.planOrderCode)
    const SizeSet = new Set(DataListP)
    for (let i = 0; i < gridOption.value.getSelectedRows().length; i++) {
        if (gridOption.value.getSelectedRows()[i].obsoleteState == 1) {
            Message.error('作废状态不可补打')
            return
        }
    }
    if (SizeSet.size > 1) {
        Message.error('请勾选相同织布单号')
        return
    }
    post({
        url: 'planSingle/clothfiy/geOldClothFiyInfo',
        data: gridOption.value.getSelectedRows().map(res => res.id)
    }).then((res: any) => {
        if (res.code == 200) {
            srcUrl.value = `./hiprint/custom3.html?model=${JSON.stringify(res.data[0].modelDetail)}&id=${JSON.stringify(gridOption.value.getSelectedRows().map(res => res.id))}`
            bfShowAdd.value = true
        }
    })
}

const bfShowAdd = ref(false)
const bc = () => {
    bfShowAdd.value = false
}
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('BoufeiList-1', gridOption, colState, tc)
const onColumnMoved = () => {
    saveGridState01()
}
const onColumnResized = () => {
    saveGridState01()
}
const onColumnVisible = () => {
    saveGridState01()
}

const timeClears = ()=>{
    queryData.tiemsData = ['','']
}
</script>
<style lang='less' scoped>
.fromTitle {
    width: 100%;
    background-color: white;
    padding: 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    form {
        width: 50% !important;
    }

    &>.my-header {
        width: 100%;
        padding: 10px;
        padding-top: 0;
        background-color: white;


        min-height: 10%;

        &>.my-tool-bar {
            text-align: right;
        }
    }
}

.fromTitle1 {
    margin-left: 50px;
    margin-top: 60px;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}
:deep(.arco-form-item-label) {
    font-size:calc(12px / var(--auto-fixMultiple))!important ;
}
:deep(.arco-checkbox) {
    font-size:calc(14px / var(--auto-fixMultiple))!important ;
}
:deep(.el-button) {
    font-size:calc(14px / var(--auto-fixMultiple))!important ;
}
:deep(.arco-btn) {
    font-size:calc(14px / var(--auto-fixMultiple))!important ;
}
:deep(.ag-header-cell-text) {
    font-size:calc(14px / var(--auto-fixMultiple))!important ;
}
:deep(.ag-cell) {
    font-size:calc(14px / var(--auto-fixMultiple))!important ;
}
</style>